<?php

namespace app\api\controller\product;

use app\common\func\Constant;
use think\Db;

/**
 * 终端
 * Class Terminal
 * @package app\api\controller\product
 */
class Terminal
{
	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config  = [
		"prefix" 	=> "fd_",
		"ter" 		=> "equip",
		"pro" 		=> "product",
		"rate"		=> "equip_rate",
		"temps"		=> "equip_rate_tplt",
		"apply" 	=> "equip_rate_mods_apply"
	];


	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 费率修改操作
	 */
	public function rate_mods_operate($uid, $proid, $typs, $sn, $appyRate, $origRate)
	{
		$reg = "0201";
		if (!empty($uid) && !empty($proid) && !empty($typs) && !empty($sn)) {
			// 查看 SN 所属
			$checkSn = Db::name($this->config["ter"])
				->where("main_id = {$uid} and product_id = {$proid} and sn = '{$sn}'")
				->count();
			if ($checkSn) {
				if (!is_numeric($appyRate) && !is_numeric($origRate)) {
					$reg = "0203";
				} else {
					$arr = $this->rate_mods_template($proid, $typs, $sn);
					if ($arr["mini"] > $appyRate || $arr["maxi"] < $appyRate) {
						$reg = "0204";
					} else {
						// 查看 默认费率 修改状态
						$setCheck = true;
						if ($typs == "D") {
							$deSetCheck = Db::name($this->config["rate"])
								->where("proid = {$proid} and sn = '{$sn}' and state = '{$typs}' and isModfy = '1'")
								->count();
							if ($deSetCheck) {
								$setCheck = false;
								$reg = "0205";
							}
						}
						if ($setCheck) {
							$data = [];
							$where = [];
							$data = [
								"agid" => $uid,
								"pro_id" => $proid,
								"sn" => $sn,
								"apply_typs" => $typs,
								"appy_rate" => $appyRate,
								"orig_rate" => $origRate,
								"is_apply" => 2,
								"create_time" => time()
							];
							$flag = false;
							$where = ["agid" => $uid, "pro_id" => $proid, "sn" => $sn, "apply_typs" => $typs, "status" => 1];
							if ($typs == 'D') {
								$reg = "0302";
								$isExist = Db::name($this->config["apply"])->where($where)->count();
								if (!$isExist) {
									$flag = true;
								}
							} else if ($typs == 'T') {
								$reg = "0305";
								// 查看 是否有待确认订单
								$where["is_apply"] = 2;
								$isExist = Db::name($this->config["apply"])->where($where)->count();
								if (!$isExist) {
									$nums = 1;
									$where["is_apply"] = 1;
									$check_pric = Db::name($this->config["apply"])->where($where)->count();
									if ($check_pric) {
										$nums += Db::name($this->config["apply"])->where($where)->max("nums");
									}
									$data["nums"] = $nums;
									$flag = true;
								}
							}
							if ($flag) {
								$reg = "0301";
								$id = Db::name($this->config["apply"])->insertGetId($data);
								if ($id) {
									$reg = "0300";
								}
							}
						}
					}
				}
			} else {
				$reg = "0206";
			}
		}
		return $reg;
	}


	/**
	 * 是否有终端
	 */
	public function check($uid, $proid)
	{
		if (!empty($uid) && !empty($proid)) {
			$check = Db::name($this->config["ter"])
				->where("main_id = {$uid} and product_id = {$proid}")
				->count();
			if ($check) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 查看是否设置 模板
	 */
	public function check_mods_rate_template($proid, $typs)
	{
		if (!empty($proid) && !empty($typs)) {
			$check = Db::name($this->config["temps"])
				->where("pro_id = {$proid} and typs = '{$typs}' and state = 1")
				->count();
			if ($check) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 费改 - 模板
	 */
	public function rate_mods_template($proid, $typs, $sn = "")
	{
		if (!empty($typs) && !empty($proid)) {
			$return = [];
			if ($typs == 'D') {
				$check = $this->check_mods_rate_template($proid, $typs);
				if ($check) {
					$where = "pro_id = {$proid} and typs = '{$typs}' and state = 1";
					$return = Db::name($this->config["temps"])->where($where)->field("round(mini ,2) mini, round(maxi,2) maxi")->find();
				} else {
					$return = ["mini" => Constant::$minRate[$proid], "maxi" => Constant::$defaultRate[$proid]];
				}
			} else if ($typs == 'T') {
				$mini = "";
				$mini = Constant::$defaultRate[$proid];
				$where = ["sn" => $sn, "state" => $typs];
				$check_price_rate = Db::name($this->config["rate"])->where($where)->count();
				if ($check_price_rate) {
					$price_rate = Db::name($this->config["rate"])->where($where)->max("rate");
					$mini =  sprintf("%01.2f", $price_rate);;
				} else {
					$where["state"] = 'D';
					$default_rate = Db::name($this->config["rate"])->where($where)->value("rate");
					$mini = sprintf("%01.2f", $default_rate);
				}
				$return = ["mini" => $mini, "maxi" => Constant::$maxRate[$proid]];
			}
			return $return;
		}
		return false;
	}

	/**
	 * 调价费率修改 - 列表
	 */
	public function modi_read_price_rate_data($uid, $proid, $typs, $page = 1, $isMod = 0, $sn = "")
	{
		$data = [];
		if (!empty($uid) && !empty($typs)) {
			$now = strtotime(date("Y-m-d", time()));
			$proWhere = "";
			if ($proid) $proWhere = "id = {$proid}";
			$proArr = Db::name($this->config["pro"])
				->where($proWhere)
				->field("id, name")
				->select();
			if ($proArr) {
				foreach ($proArr as $vals) {
					$days = 0;
					$where = "";
					$check = $this->check($uid, $vals["id"]);
					if ($check) {
						$days = $this->_get_typs_limits_days($vals["id"], $typs);
						if (!empty($sn)) $where .= " AND sn = '{$sn}' ";

						$field = "product_id,main_id,sn,ifnull(user_info,'未知') merchs,";
						$field .= "if( CAST( UNIX_TIMESTAMP( DATE_SUB(DATE_ADD( FROM_UNIXTIME( binding_time, '%Y-%m-%d' ), INTERVAL {$days} DAY ),INTERVAL 1 DAY) ) AS UNSIGNED ) < {$now}, 0, 1 ) isMod,";
						$field .= "FROM_UNIXTIME( binding_time, '%Y-%m-%d' ) st,";
						$field .= "DATE_SUB( DATE_ADD( FROM_UNIXTIME( binding_time, '%Y-%m-%d' ), INTERVAL {$days} DAY ), INTERVAL 1 DAY ) ens ";

						$calcSql =  Db::name($this->config["ter"])->where("main_id = {$uid} and  binding_time > 0 and product_id = " . $vals["id"] . $where)->field($field)->buildSql(true);

						$query = Db::table($calcSql)->alias('a')->where("isMod = {$isMod}")->select();
						if ($query) {
							foreach ($query as $queVal) {
								$queVal["name"] = $vals["name"];
								$queVal["rate"] = $this->_get_prices_rate($queVal["product_id"], $queVal["sn"]);
								$queVal["isOperate"] =  $queVal["isMod"];
								array_push($data, $queVal);
							}
						}
					}
				}
			}
		}
		$page_data = \app\api\controller\basics\Basics::instance()->array_page($data, $page);
		return $page_data;
	}

	/**
	 * 获取费率
	 */
	public function _get_prices_rate($proid, $sn)
	{
		$rate = "0.60";
		if (!empty($sn)) {
			$where = ["proid" => $proid, "sn" => $sn, "state" => "T"];
			$check = Db::name($this->config["rate"])
				->where($where)
				->count();
			if ($check) {
				$rate = Db::name($this->config["rate"])->where($where)->max("rate");
			} else {
				$where["state"] = "D";
				$check = Db::name($this->config["rate"])
					->where($where)
					->count();
				if ($check) {
					$rate = Db::name($this->config["rate"])->where($where)->value("rate");
				}
			}
		}
		return $rate;
	}

	/**
	 * 默认费率修改 - 列表
	 */
	public function modi_default_rate_data($uid, $proid, $typs, $page = 1, $isMod = 0, $sn = "")
	{
		$data = [];
		if (!empty($uid) && !empty($typs)) {
			$now = strtotime(date("Y-m-d", time()));
			$proWhere = "";
			if ($proid) $proWhere = "id = {$proid}";
			$proArr = Db::name($this->config["pro"])
				->where($proWhere)
				->field("id, name")
				->select();
			if ($proArr) {
				foreach ($proArr as $key => $vals) {
					$check = $this->check($uid, $vals["id"]);
					if ($check) {
						$days = 0;
						$where = "";
						$joinSql = "";
						$selectSql = "";
						$returnSql = "";
						$days = $this->_get_typs_limits_days($vals["id"], $typs);
						if (!empty($sn)) $where .= " AND sn = '{$sn}'";
						$joinSql = "SELECT
										product_id,main_id,sn,ifnull( isApply, 0 ) isApply,ifnull( ROUND( rate, 2 ), '0.60' ) rate,orig_rate,appy_rate,
										ifnull( user_info, '未知' ) merchs,ifnull( snNo, sn ) er,isModfy,
										IF( CAST( UNIX_TIMESTAMP( DATE_ADD( FROM_UNIXTIME( binding_time, '%Y-%m-%d' ), INTERVAL {$days} DAY ) ) AS UNSIGNED ) > {$now}, 0, 1 ) mods,
										FROM_UNIXTIME( binding_time, '%Y-%m-%d' ) st,
										DATE_SUB( DATE_ADD( FROM_UNIXTIME( binding_time, '%Y-%m-%d' ), INTERVAL {$days} DAY ), INTERVAL 1 DAY ) ens,
										takeTimes 
									FROM
										fd_equip e
										LEFT JOIN ( SELECT sn snNo,isModfy,rate,IF(modify_time = 0,0,FROM_UNIXTIME( modify_time, '%Y-%m-%d %H:%i:%s' )) takeTimes FROM fd_equip_rate WHERE state = 'D' ) r ON e.sn = r.snNo
										LEFT JOIN ( SELECT orig_rate,appy_rate, sn apSn, is_apply isApply FROM fd_equip_rate_mods_apply WHERE apply_typs = 'D' AND `status` = 1 ) ap ON e.sn = ap.apSn 
									WHERE main_id = {$uid} AND binding_time > 0 AND product_id = " . $vals["id"] . " {$where}
									ORDER BY binding_time ASC ";
						$selectSql = "SELECT
										main_id,product_id,sn,isApply,rate,orig_rate orgRate,merchs,isModfy,mods,st,ens,takeTimes,appy_rate,
										if( isModfy = '1', 1 , if (isApply = 0 , mods , 1) ) isMod,	
										IF(isModfy = '1','已生效', IF(isApply = 0,if(mods = 1 , '已超时' , '未申请'),IF(isApply = 1,'生效中',IF( isApply = 2, '待审核', '申请驳回' ) ))) nick,
										IF(isModfy = '1',1, IF(isApply = 0,if(mods = 1 ,2 , 3),IF(isApply = 1,4,IF( isApply = 2, 5, 6 ) ))) isOperate
									FROM
										({$joinSql}) a";
						$returnSql = "SELECT * FROM ({$selectSql}) b WHERE isMod = {$isMod}";
						$query = Db::query($returnSql);
						if ($query) {
							foreach ($query as $qurVal) {
								$qurVal["name"] = $vals["name"];
								if($qurVal["isMod"] == 0){
									$qurVal["orgRate"] = $qurVal["rate"];
								}
								if (in_array($qurVal["isOperate"], [1, 4, 5])) {
									$qurVal["rate"] = $qurVal["appy_rate"];
								}
								
								array_push($data, $qurVal);
							}
						}
					}
				}
			}
		}
		$page_data = \app\api\controller\basics\Basics::instance()->array_page($data, $page);
		return $page_data;
	}

	/**
	 * 受限天数
	 */
	public function _get_typs_limits_days($proid, $typs)
	{
		$day = 0;
		switch ($typs) {
			case 'D':
				$day = Constant::$editRateDayLimit[$proid];
				break;
			case 'T':
				$day = Constant::$adjustRateDayLimit[$proid];
				break;
		}
		return $day;
	}
}
